var app = getApp()

Page({

  data: {
    imgUrl: '',
    bgImgUrl: '',
    width: 0,
    height: 0,
    flags: {},
  },

  onLoad: function(options) {
    wx.showLoading({
      title: '图片生成中...',
      icon: 'loading',
    })
    this.setData({
      imgUrl: options.imgUrl
    })
    this.getConfig()
  },

  getConfig: function() {
    var that = this
    wx.request({
      url: app.globalData.url + 'config/v/' + app.globalData.version,
      success: function(res) {
        that.setData({
          bgImgUrl: res.data.msg,
          flags: res.data.data
        })
        that.drawCanvas()
      }
    })
  },

  drawCanvas: function() {
    var that = this
    var canvas = wx.createCanvasContext('canvas')
    canvas.setFillStyle('#fff')
    canvas.fillRect(0, 0, 300, 800)
    wx.getImageInfo({
      src: that.data.imgUrl,
      success: function(res) {
        that.setData({
          width: res.width,
          height: res.height
        })
        canvas.drawImage(res.path, 0, 0, res.width, res.height)
        canvas.draw()
        that.setT()
      }
    })
  },

  setT: function() {
    var that = this
    setTimeout(function() {
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        success: function(res) {
          that.setData({
            imgUrl: res.tempFilePath,
          })
          wx.hideLoading()
        },
        fail: function(res) {
          wx.hideLoading()
        }
      })
    }, 300)
  },

  previewImg: function(e) {
    var img = this.data.imgUrl
    wx.previewImage({
      current: img,
      urls: [img]
    })
  },

  onShareAppMessage: function() {
    return {
      title: '创作属于你的艺术!',
      imageUrl: '/images/share.png',
      path: '/pages/index/index'
    }
  },

  save: function() {
    var that = this;
    wx.showLoading({
      mask: true,
      title: "保存中"
    })
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imgUrl,
      success: (res) => {
        wx.hideLoading()
        wx.showModal({
          title: "保存成功",
          content: "图片已经保存到手机相册，将图片分享给朋友吧~",
          showCancel: false
        })
      },
      fail: function(error) {
        wx.hideLoading();
        wx.openSetting({
          success(settingdata) {
            console.log(settingdata)
            if (settingdata.authSetting['scope.writePhotosAlbum']) {
              console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
            } else {
              console.log('获取权限失败，给出不给权限就无法正常使用的提示')
            }
          }
        })
      }
    })
  },
})